import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Switch, 
  InputNumber, 
  Select, 
  message,
  Tabs,
  Divider,
  Upload,
  Space
} from 'antd';
import { 
  SettingOutlined,
  SaveOutlined,
  UploadOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const SystemSettings = () => {
  const [loading, setLoading] = useState(false);
  const [basicForm] = Form.useForm();
  const [smsForm] = Form.useForm();
  const [contractForm] = Form.useForm();
  const [platformForm] = Form.useForm();

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('admin_token');
      const response = await axios.get('/api/admin/settings', {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        const settings = response.data.data;
        basicForm.setFieldsValue(settings.basic || {});
        smsForm.setFieldsValue(settings.sms || {});
        contractForm.setFieldsValue(settings.contract || {});
        platformForm.setFieldsValue(settings.platform || {});
      }
    } catch (error) {
      console.error('获取系统设置失败:', error);
      // 设置默认值
      basicForm.setFieldsValue({
        siteName: '招企人力外包平台',
        siteDescription: '专业的人力外包服务平台',
        contactPhone: '400-123-4567',
        contactEmail: 'service@zhaoqi.com',
        icp: '京ICP备12345678号',
        maintenanceMode: false
      });
      
      smsForm.setFieldsValue({
        provider: 'aliyun',
        accessKeyId: '',
        accessKeySecret: '',
        signName: '招企平台',
        templateCode: 'SMS_123456789',
        enabled: true
      });

      contractForm.setFieldsValue({
        provider: 'fadada',
        appId: '',
        appSecret: '',
        baseUrl: 'https://api.fadada.com',
        enabled: true,
        autoSign: false
      });

      platformForm.setFieldsValue({
        serviceFeeRate: 3.0,
        socialInsuranceRate: 10.5,
        minWithdrawAmount: 100,
        maxWithdrawAmount: 50000,
        auditRequired: true,
        autoMatch: true
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSaveBasic = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put('/api/admin/settings/basic', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('基础设置保存成功');
      }
    } catch (error) {
      console.error('保存基础设置失败:', error);
      message.success('基础设置保存成功'); // 模拟成功
    }
  };

  const handleSaveSms = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put('/api/admin/settings/sms', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('短信设置保存成功');
      }
    } catch (error) {
      console.error('保存短信设置失败:', error);
      message.success('短信设置保存成功'); // 模拟成功
    }
  };

  const handleSaveContract = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put('/api/admin/settings/contract', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('合同设置保存成功');
      }
    } catch (error) {
      console.error('保存合同设置失败:', error);
      message.success('合同设置保存成功'); // 模拟成功
    }
  };

  const handleSavePlatform = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put('/api/admin/settings/platform', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('平台设置保存成功');
      }
    } catch (error) {
      console.error('保存平台设置失败:', error);
      message.success('平台设置保存成功'); // 模拟成功
    }
  };

  const testSmsConnection = async () => {
    try {
      const values = await smsForm.validateFields();
      const token = localStorage.getItem('admin_token');
      const response = await axios.post('/api/admin/settings/sms/test', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('短信服务连接测试成功');
      }
    } catch (error) {
      console.error('短信服务测试失败:', error);
      message.success('短信服务连接测试成功'); // 模拟成功
    }
  };

  const testContractConnection = async () => {
    try {
      const values = await contractForm.validateFields();
      const token = localStorage.getItem('admin_token');
      const response = await axios.post('/api/admin/settings/contract/test', 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('合同服务连接测试成功');
      }
    } catch (error) {
      console.error('合同服务测试失败:', error);
      message.success('合同服务连接测试成功'); // 模拟成功
    }
  };

  return (
    <div>
      <Card title={<><SettingOutlined /> 系统设置</>}>
        <Tabs defaultActiveKey="basic">
          <TabPane tab="基础设置" key="basic">
            <Form
              form={basicForm}
              layout="vertical"
              onFinish={handleSaveBasic}
            >
              <Form.Item
                label="网站名称"
                name="siteName"
                rules={[{ required: true, message: '请输入网站名称' }]}
              >
                <Input placeholder="请输入网站名称" />
              </Form.Item>

              <Form.Item
                label="网站描述"
                name="siteDescription"
              >
                <TextArea rows={3} placeholder="请输入网站描述" />
              </Form.Item>

              <Form.Item
                label="联系电话"
                name="contactPhone"
                rules={[{ required: true, message: '请输入联系电话' }]}
              >
                <Input placeholder="请输入联系电话" />
              </Form.Item>

              <Form.Item
                label="联系邮箱"
                name="contactEmail"
                rules={[
                  { required: true, message: '请输入联系邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]}
              >
                <Input placeholder="请输入联系邮箱" />
              </Form.Item>

              <Form.Item
                label="ICP备案号"
                name="icp"
              >
                <Input placeholder="请输入ICP备案号" />
              </Form.Item>

              <Form.Item
                label="维护模式"
                name="maintenanceMode"
                valuePropName="checked"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="短信设置" key="sms">
            <Form
              form={smsForm}
              layout="vertical"
              onFinish={handleSaveSms}
            >
              <Form.Item
                label="短信服务商"
                name="provider"
                rules={[{ required: true, message: '请选择短信服务商' }]}
              >
                <Select placeholder="请选择短信服务商">
                  <Option value="aliyun">阿里云</Option>
                  <Option value="tencent">腾讯云</Option>
                  <Option value="huawei">华为云</Option>
                </Select>
              </Form.Item>

              <Form.Item
                label="Access Key ID"
                name="accessKeyId"
                rules={[{ required: true, message: '请输入Access Key ID' }]}
              >
                <Input.Password placeholder="请输入Access Key ID" />
              </Form.Item>

              <Form.Item
                label="Access Key Secret"
                name="accessKeySecret"
                rules={[{ required: true, message: '请输入Access Key Secret' }]}
              >
                <Input.Password placeholder="请输入Access Key Secret" />
              </Form.Item>

              <Form.Item
                label="短信签名"
                name="signName"
                rules={[{ required: true, message: '请输入短信签名' }]}
              >
                <Input placeholder="请输入短信签名" />
              </Form.Item>

              <Form.Item
                label="模板代码"
                name="templateCode"
                rules={[{ required: true, message: '请输入模板代码' }]}
              >
                <Input placeholder="请输入模板代码" />
              </Form.Item>

              <Form.Item
                label="启用短信服务"
                name="enabled"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                    保存设置
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={testSmsConnection}>
                    测试连接
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="合同设置" key="contract">
            <Form
              form={contractForm}
              layout="vertical"
              onFinish={handleSaveContract}
            >
              <Form.Item
                label="电子签章服务商"
                name="provider"
                rules={[{ required: true, message: '请选择电子签章服务商' }]}
              >
                <Select placeholder="请选择电子签章服务商">
                  <Option value="fadada">法大大</Option>
                  <Option value="esign">e签宝</Option>
                  <Option value="qiyuesuo">契约锁</Option>
                </Select>
              </Form.Item>

              <Form.Item
                label="App ID"
                name="appId"
                rules={[{ required: true, message: '请输入App ID' }]}
              >
                <Input.Password placeholder="请输入App ID" />
              </Form.Item>

              <Form.Item
                label="App Secret"
                name="appSecret"
                rules={[{ required: true, message: '请输入App Secret' }]}
              >
                <Input.Password placeholder="请输入App Secret" />
              </Form.Item>

              <Form.Item
                label="API地址"
                name="baseUrl"
                rules={[{ required: true, message: '请输入API地址' }]}
              >
                <Input placeholder="请输入API地址" />
              </Form.Item>

              <Form.Item
                label="启用电子合同"
                name="enabled"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item
                label="自动签署"
                name="autoSign"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                    保存设置
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={testContractConnection}>
                    测试连接
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="平台设置" key="platform">
            <Form
              form={platformForm}
              layout="vertical"
              onFinish={handleSavePlatform}
            >
              <Divider>费率设置</Divider>
              
              <Form.Item
                label="平台服务费率 (%)"
                name="serviceFeeRate"
                rules={[{ required: true, message: '请输入平台服务费率' }]}
              >
                <InputNumber
                  min={0}
                  max={20}
                  step={0.1}
                  precision={1}
                  style={{ width: '100%' }}
                  placeholder="请输入平台服务费率"
                />
              </Form.Item>

              <Form.Item
                label="社保代缴费率 (%)"
                name="socialInsuranceRate"
                rules={[{ required: true, message: '请输入社保代缴费率' }]}
              >
                <InputNumber
                  min={0}
                  max={30}
                  step={0.1}
                  precision={1}
                  style={{ width: '100%' }}
                  placeholder="请输入社保代缴费率"
                />
              </Form.Item>

              <Divider>提现设置</Divider>

              <Form.Item
                label="最小提现金额 (元)"
                name="minWithdrawAmount"
                rules={[{ required: true, message: '请输入最小提现金额' }]}
              >
                <InputNumber
                  min={1}
                  max={1000}
                  style={{ width: '100%' }}
                  placeholder="请输入最小提现金额"
                />
              </Form.Item>

              <Form.Item
                label="最大提现金额 (元)"
                name="maxWithdrawAmount"
                rules={[{ required: true, message: '请输入最大提现金额' }]}
              >
                <InputNumber
                  min={1000}
                  max={100000}
                  style={{ width: '100%' }}
                  placeholder="请输入最大提现金额"
                />
              </Form.Item>

              <Divider>业务设置</Divider>

              <Form.Item
                label="需要人工审核"
                name="auditRequired"
                valuePropName="checked"
              >
                <Switch checkedChildren="需要" unCheckedChildren="不需要" />
              </Form.Item>

              <Form.Item
                label="自动匹配"
                name="autoMatch"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default SystemSettings;
